//
//  UIImageExt.swift
//  FaceVerify
//
//  Created by duzexu on 2017/3/6.
//  Copyright © 2017年 duzexu. All rights reserved.
//

import UIKit

extension UIImage {
    
    func compressBelowMaxLength(maxLength: Int) -> Data? {
        var ratio = 1.0
        var quality = 1.0
        var result = self;
        
        var data = UIImageJPEGRepresentation(self, CGFloat(quality))
        while (data?.count)! > maxLength {
            if ratio > quality {
                ratio -= 0.1
                if ratio <= 0 {
                    break;
                }
                result = self.scaleToScale(scale: ratio)!;
                data = UIImageJPEGRepresentation(result, CGFloat(quality));
            }else{
                if quality <= 0 {
                    break;
                }
                quality -= 0.1;
                data = UIImageJPEGRepresentation(result, CGFloat(quality));
            }
        }
        return data
    }
    
    
    func scaleToScale(scale: Double) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(CGSize(width: self.size.width * CGFloat(scale), height: self.size.height * CGFloat(scale)), false, UIScreen.main.scale);
        self.draw(in: CGRect(x: 0, y: 0, width: self.size.width * CGFloat(scale), height: self.size.height * CGFloat(scale)))
        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext();
        return scaledImage;
    }
    
}
